const express = require('express');
const cors = require('cors');
const path = require('path');
const { initDB } = require('./models/db');
const dataRoutes = require('./routes/dataRoutes');
const rankingRoutes = require('./routes/rankingRoutes');

require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;
const UPLOAD_DIR = process.env.UPLOAD_DIR || 'uploads/';

if (!require('fs').existsSync(UPLOAD_DIR)) {
  require('fs').mkdirSync(UPLOAD_DIR, { recursive: true });
}

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(UPLOAD_DIR));

app.use('/api/data', dataRoutes);
app.use('/api/ranking', rankingRoutes);

app.use((err, req, res, next) => {
  console.error(err.stack);
  if (err.code === 'LIMIT_FILE_SIZE') {
    return res.status(400).json({ error: `文件大小不能超过${process.env.MAX_FILE_SIZE/1024/1024}MB` });
  }
  res.status(500).json({ error: err.message || '服务器内部错误' });
});

initDB().then(() => {
  app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log(`文件上传目录: ${path.resolve(UPLOAD_DIR)}`);
  });
}).catch(err => {
  console.error('启动失败:', err);
  process.exit(1);
});